import { createRouter, createWebHashHistory } from "vue-router";
import routes from "@/router/routes.js";

import { notiFication } from "@/utils/message.js";
import { getToken } from "@/utils/setToken.js";

//引入加载条
import nprogress from "nprogress";
import "nprogress/nprogress.css";

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  nprogress.start();

  // 改变页面标题，
  document.title = to.meta.title;
  //获取token值
  const token = getToken();
  //判断是否存在token
  //token不存在且所去页面不是登录页面
  if (!token && to.path !== "/login") {
    notiFication("请先登录", "error");
    return next("/login");
  } else if (token && to.path === "/login") {
    //token存在且所去页面是登录页面
    //到本页面或者是去上一层页面
    notiFication("请勿重复登录", "error");
    return next({
      path: from.path ? from.path : "/",
    });
  }
  next();
});

router.afterEach((to, from) => {
  nprogress.done();

});
export default router;
